package com.sale.system.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sale.common.core.constant.CacheNames;
import com.sale.common.core.exception.GlobalException;
import com.sale.common.mybatis.core.page.PageQuery;
import com.sale.common.mybatis.core.page.TableDataInfo;
import com.sale.common.redis.utils.CacheUtils;
import com.sale.common.satoken.utils.LoginHelper;
import com.sale.system.api.domain.SysDictData;
import com.sale.system.api.domain.SysUser;
import com.sale.system.domain.dto.PageUrlDto;
import com.sale.system.domain.dto.SysAppConfigNodeDto;
import com.sale.system.domain.dto.SysWorkbenchAuditAgentDto;
import com.sale.system.domain.vo.SysWorkbenchAuditAgentVo;
import com.sale.system.mapper.*;
import com.sale.system.service.SysWorkbenchAuditAgentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 审核代办实现层
 */
@RequiredArgsConstructor
@Service
public class SysWorkbenchAuditAgentServiceImpl implements SysWorkbenchAuditAgentService {


    /**
     * 审核代办mapper
     */
    private final SysWorkbenchAuditAgentMapper sysWorkbenchAuditAgentMapper;

    /**
     * 审核节点mapper
     */
    private final SysAppConfigNodeMapper sysAppConfigNodeMapper;

    /**
     * 用户角色mappper
     */
    private final SysUserRoleMapper sysUserRoleMapper;

    /**
     * 菜单Service
     */
    @Resource
    SysMenuServiceImpl iSysMenuService;

    /**
     * 菜单Mapper
     */
    private final SysMenuMapper sysMenuMapper;

    /**
     * 用户Mapper
     */
    private final SysUserMapper sysUserMapper;

    /**
     * 审核代办分页列表
     *
     * @param sysWorkbenchAuditAgentVo
     * @return
     */
    @Override
    public TableDataInfo<SysWorkbenchAuditAgentDto> getList(SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo, PageQuery pageQuery) {
        //获取审核代办状态
        List<SysDictData> statusArray = CacheUtils.get(CacheNames.SYS_DICT, "audit_agent_status");
        Map<String, String> statusMap = statusArray.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));

        sysWorkbenchAuditAgentVo.setUserId(LoginHelper.getUserId());
        Page<SysWorkbenchAuditAgentDto> auditAgentList = sysWorkbenchAuditAgentMapper.getAuditAgentList(sysWorkbenchAuditAgentVo, pageQuery.build());
        List<SysWorkbenchAuditAgentDto> records = auditAgentList.getRecords();
        for (SysWorkbenchAuditAgentDto entity : records) {
            //状态
            entity.setStatusDict(statusMap.get(entity.getStatus()));
        }
        return TableDataInfo.build(auditAgentList);
    }

    /**
     * 新增审核单据消息提醒
     *
     * @param sysWorkbenchAuditAgentVo
     * @return
     */
    @Override
    public boolean insertAuditAgent(SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo) {

        //通过权限码查出当前单据对应的审核用户id和角色id集合
        List<SysAppConfigNodeDto> list = sysAppConfigNodeMapper.getUserAndRole(sysWorkbenchAuditAgentVo.getDocConfig());

        //用户id集合
        List<String> userIdList = new ArrayList<>();

        for (SysAppConfigNodeDto sysAppConfigNodeDto : list) {
            //用户id字符串
            String nodeUserId = sysAppConfigNodeDto.getNodeUserId();

            String[] users = nodeUserId.split(",");

            userIdList.addAll(Arrays.asList(users));

            String nodeRoleId = sysAppConfigNodeDto.getNodeRoleId();

            String[] roles = nodeRoleId.split(",");

            //通过角色id查出用户列表
            List<Long> sysUserRole = sysUserRoleMapper.getUserList(roles);

            List<String> arrayList = new ArrayList<>();

            for (Long aLong : sysUserRole) {
                arrayList.add(String.valueOf(aLong));
            }

            userIdList.addAll(arrayList);

        }

        //通过权限码查出菜单id
        Long id = sysMenuMapper.getIdByPermissionName(sysWorkbenchAuditAgentVo.getDocConfig());

        //通过页面名称拿到路由
        //UrlAndIconDto menuUrl = iSysMenuService.getMenuUrl(id);
        //路由
        //String menuUrl1 = menuUrl.getMenuUrl();

        List<PageUrlDto> pageUrlList = sysMenuMapper.getPageUrlList(id);

        String menuUrl1 = "/";

        for (int i = 0; i < pageUrlList.size(); i++) {
            menuUrl1 = menuUrl1 + pageUrlList.get(i).getPageUrl();

            if (i != pageUrlList.size() - 1) {
                menuUrl1 = menuUrl1 + "/";
            }
        }

        //创建审核消息提醒集合
        List<SysWorkbenchAuditAgentVo> auditList = new ArrayList<>();

        if ("1".equals(sysWorkbenchAuditAgentVo.getPassFlag())) {
            userIdList.clear();


            SysUser sysUser = sysUserMapper.getByUserName(sysWorkbenchAuditAgentVo.getCreateName());
            userIdList.add(String.valueOf(sysUser.getUserId()));

            updateStatus(3, sysWorkbenchAuditAgentVo.getReceiptNumber(), sysWorkbenchAuditAgentVo.getReceiptName());
        }

        for (String userId : userIdList) {
            SysWorkbenchAuditAgentVo sysWorkbenchAuditAgentVo1 = new SysWorkbenchAuditAgentVo();

            sysWorkbenchAuditAgentVo1.setReceiptName(sysWorkbenchAuditAgentVo.getReceiptName());//单据名称
            sysWorkbenchAuditAgentVo1.setReceiptNumber(sysWorkbenchAuditAgentVo.getReceiptNumber());//单据号
            sysWorkbenchAuditAgentVo1.setStatus(sysWorkbenchAuditAgentVo.getStatus());//状态
            sysWorkbenchAuditAgentVo1.setReceiptContent(sysWorkbenchAuditAgentVo.getReceiptContent());//内容
            sysWorkbenchAuditAgentVo1.setCreateTime(new Date());//创建时间
            sysWorkbenchAuditAgentVo1.setUserId(Long.valueOf(userId));//用户id
            sysWorkbenchAuditAgentVo1.setPageUrl(menuUrl1);//页面路径

            auditList.add(sysWorkbenchAuditAgentVo1);

        }
        if (auditList.size() > 0) {
            return sysWorkbenchAuditAgentMapper.insertAuditAgent(auditList);
        }else {
            throw new GlobalException("未进行审核配置，无法生成代办信息");
        }

    }

    /**
     * 修改审核单据状态
     *
     * @param status,receiptNumber
     * @return
     */
    @Override
    public boolean updateStatus(int status, String receiptNumber, String modelName) {
        return sysWorkbenchAuditAgentMapper.updateStatus(status, receiptNumber, modelName);
    }

    /**
     * 删除审核代办
     *
     * @param receiptNumber
     * @return
     */
    @Override
    public boolean deleteDoc(String receiptNumber, String modelName) {
        boolean b = sysWorkbenchAuditAgentMapper.deleteDoc(receiptNumber, modelName);
        return b;
    }
}
